﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Collections;

namespace Fwk.Presentacion
{
    public class PaginaBase: System.Web.UI.Page
    {
        #region FindControl
        //la variable T puede ser un control
        // T me devuelve el control que le especifico en el parametro
        public T Find<T>(string id) where T : Control
        {
            return (T)FindControl(id);
        }

        public override Control FindControl(string id)
        {
            Control bc = null;
            try
            {
                bc = base.FindControl(id);
            }
            catch (HttpException)
            {
                bc = null;
            }
            return (bc != null) ? bc : PaginaBase.FindControl(id, this.Controls);
        }

        public static Control FindControl(string id, ControlCollection col)
        {
            foreach (Control c in col)
            {
                Control child = PaginaBase.FindControlRecursive(c, id);
                if (child != null)
                    return child;
            }
            return null;
        }

        private static Control FindControlRecursive(Control root, string id)
        {
            if (root.ID != null && root.ID == id)
                return root;

            foreach (Control c in root.Controls)
            {
                Control rc = PaginaBase.FindControlRecursive(c, id);
                if (rc != null)
                    return rc;
            }
            return null;
        }

        public static ArrayList FindControls(Type type, ControlCollection col)
        {
            ArrayList list = new ArrayList();
            foreach (Control c in col)
            {
                if (c.GetType() == type)
                    list.Add(c);
                else
                    PaginaBase.FindControlsRecursive(c, type, ref list);
            }
            return list;
        }

        private static void FindControlsRecursive(Control root, Type type, ref ArrayList list)
        {
            if (root.Controls.Count != 0)
            {
                foreach (Control c in root.Controls)
                {
                    if (c.GetType() == type)
                        list.Add(c);
                    else if (c.HasControls())
                        PaginaBase.FindControlsRecursive(c, type, ref list);
                }
            }
        }
        #endregion

    }
}
